﻿using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Security.Cryptography;
using System.IO;
using System.Text;

namespace DotNet.Common
{
    public class DESCrypt
    {
         public DESCrypt()
        {
            //
            // TODO: 在此处添加构造函数逻辑
            //
        }
        //0-255范围的字节数
        
        static private byte[] Key24 = new byte[] { 25, 79, 36, 99, 167, 63, 42, 86, 246, 79, 36, 99, 167, 93, 42, 106, 93, 156, 78, 65, 218, 32, 55, 99 };
        static private byte[] IV24 = new byte[] { 96, 208, 32, 55, 103, 206, 79, 36, 99, 107, 210, 42, 56, 216, 79, 36, 99, 167, 203, 42, 86, 93, 126, 78 };

        static public string Crypt(string p)
        {
            if (p != "")
            {
                TripleDESCryptoServiceProvider des = new TripleDESCryptoServiceProvider();
                MemoryStream ms = new MemoryStream();
                CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(Key24, IV24), CryptoStreamMode.Write);
                StreamWriter sw = new StreamWriter(cs);
                sw.Write(p);
                sw.Flush();
                cs.FlushFinalBlock();
                ms.Flush();
                return Convert.ToBase64String(ms.GetBuffer(), 0, Convert.ToInt32(ms.Length)).Replace("/","@@@XXX").Replace("=","@@@DDD").Replace("*","###XXX");
            }
            else
            {
                return "";
            }
        }

        static public string DeCrypt(string p)
        {
            if (p != "")
            {
                p = p.Replace("@@@XXX","/").Replace("@@@DDD","=").Replace("###XXX","*");
                TripleDESCryptoServiceProvider des = new TripleDESCryptoServiceProvider();
                byte[] buffer = Convert.FromBase64String(p);
                MemoryStream ms = new MemoryStream(buffer);
                CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(Key24, IV24), CryptoStreamMode.Read);
                StreamReader sr = new StreamReader(cs);
                return sr.ReadToEnd();
            }
            else
            {
                return "";
            }
        }
    }
}
